<template>
  <section class="login-main" ref="loginmain">
    <section class="main-form">
      <img class="page-logo" src="./images/logo.png"/>
      <section class="form-inner">
        <section class="form">
          <yd-cell-group>
            <template v-if="loginType === 'code'">
              <yd-cell-item>
                <yd-input
                    slot="right"
                    v-model.trim="form.phoneNumber"
                    ref="mobile"
                    required
                    id="phoneNumber"
                    :show-success-icon="false"
                    :show-error-icon="false"
                    regex="mobile"
                    placeholder="请输入手机号"></yd-input>
              </yd-cell-item>
              <yd-cell-item class="sms-code">
                <yd-input
                    slot="right"
                    v-model.trim="form.smsCode"
                    required
                    :max="6"
                    id="code"
                    :show-success-icon="false"
                    :show-error-icon="false"
                    :show-clear-icon="false"
                    placeholder="请输入短信验证码"></yd-input>
                <section v-if="phonecodeshow" slot="right" class="identifying" @click="identifying">
                  {{ identifyingcodePhone }}
                </section>
                <section v-if="!phonecodeshow" slot="right" class="identifying">重新发送({{ phonecount }}s)</section>
              </yd-cell-item>
            </template>
            <template v-else>
              <yd-cell-item>
                <yd-input
                    slot="right"
                    max="11"
                    v-model.trim="phoneNumber"
                    id="phoneNumber"
                    ref="userName"
                    required
                    :show-success-icon="false"
                    :show-error-icon="false"
                    placeholder="请输入手机号"></yd-input>
              </yd-cell-item>
              <yd-cell-item>
                <yd-input
                    id="password"
                    slot="right"
                    type="password"
                    min="6"
                    max="20"
                    v-model="password"
                    required
                    :show-success-icon="false"
                    :show-error-icon="false"
                    :class="{
                  iosPwd: clientType != 'Android' && password.length > 0,
                }"
                    placeholder="请输入密码"
                ></yd-input>
              </yd-cell-item>
            </template>
          </yd-cell-group>
        </section>
        <section class="btns">
          <section class="btns-item">
            <div v-if="loginType=='code'" class="item-btn" @click="loginType='acc'">账号密码登录</div>
            <template v-else>
              <div class="item-btn" @click="loginType='code'">手机验证码登录</div>
              <div class="item-btn">
                <router-link to="/resetPwd">忘记密码?</router-link>
              </div>
            </template>
          </section>
          <yd-button size="large" type="primary" :class="[!agree && 'disabled']" class="loginBtn" @click.native="login()">登录</yd-button>
          <section class="check-agreement">
            <van-checkbox v-model="agree"></van-checkbox>
            阅读并同意 <span @click="seeAgreement(1)"> 《用户协议》</span>和 <span @click="seeAgreement(2)">《隐私政策》</span>
          </section>
        </section>
      </section>
    </section>
    <section v-if="show" class="form-bottom" :class="{ auto: auto }">
      <section class="form-footer">
        <section class="footer-item">
          <section class="item-label">主办单位 ：中华全国总工会</section>
          <section class="item-label">技术支持：中慧智工新媒体科技有限公司</section>
          <section class="item-label">内容支持：《中国工人》杂志社</section>
        </section>
      </section>
    </section>
    <van-popup class="agreement-popup" v-model="showAgreement">
      <div class="agreement-container">
        <section class="iframe-container">
          <iframe v-if="showAgreement" :src="agreementPath" frameborder="0" class="agreement-text"></iframe>
        </section>
        <van-button class="agreement-btn" @click="showAgreement = false">我已阅读</van-button>
      </div>
    </van-popup>
  </section>
</template>

<script>
import url from '@/views/login/api'
import {Dialog} from 'vant'
import {phone, password} from '@/common/validate'

export default {
  name: 'Login',
  components: {[Dialog.Component.name]: Dialog.Component},
  data: () => {
    return {
      timer: null,
      phoneNumber: '',
      password: '', // 密码
      clientType: localStorage.getItem('sys'),
      logosrc: '/API-ENTERPRISE-APP/app/sysConfig/fileDownloadByName?name=APP_LOGIN_LOGO',
      identifyingcodePhone: '发送验证码',
      phonecodeshow: true,
      phonecount: '',
      phonetimer: null,
      form: {
        phoneNumber: '',
        smsCode: ''
      },
      auto: false,
      show: true,
      loginType: 'code',
      agree: false,
      showAgreement: false,
      agreementPath: ''
    }
  },
  methods: {
    /**
     * 打开协议弹框  t = 1 用户协议   2：隐私协议
     */
    seeAgreement(t) {
      this.agreementPath = t === 1 ? `yhxy.html` : `yszc.html`
      this.showAgreement = true
    },
    PhoneVerify() {
      if (this.form.phoneNumber === '') {
        this.$dialog.toast({
          mes: '请输入手机号码！',
          timeout: 1500
        })
        return false
      }
      if (!phone(this.form.phoneNumber)) {
        this.$dialog.toast({
          mes: '请输入正确的手机号',
          timeout: 1500,
          icon: 'none'
        })
        return
      }
      return true
    },
    /**
     * 0：密码重置   1：注册   2：修改手机号  3：修改邮箱，4：登录
     * */
    identifying() {
      if (this.PhoneVerify()) {
        if (!this.codeTimer) {
          const _this = this
          const data = {
            phoneNumber: this.form.phoneNumber.trim(),
            reqTime: new Date().Format('yyyy-MM-dd hh:mm:ss')
          }
          const signStr = JSON.stringify(data)
          this.$dialog.loading.open('短信发送中...')
          this.$axios.post(url.sendcode, {param: this.$getRsaCode(signStr)}).then(res => {
            this.$dialog.loading.close()
            if (res.code && res.code === '200') {
              this.$dialog.toast({
                mes: '短信已发送，请注意查收！',
                timeout: 1500
              })
              const TIME_COUNT = 60
              if (!_this.phonetimer) {
                _this.phonecount = TIME_COUNT
                _this.phonecodeshow = false
                _this.phonetimer = setInterval(() => {
                  if (_this.phonecount > 0 && _this.phonecount <= TIME_COUNT) {
                    _this.phonecount--
                  } else {
                    _this.phonecodeshow = true
                    clearInterval(_this.phonetimer)
                    _this.phonetimer = null
                  }
                }, 1000)
              }
            }else if (res.code === '8888' || res.code === 8888) {
              Dialog.confirm({
                title: '提示',
                message: res.msg,
                confirmButtonText: '找回手机号',
                cancelButtonText: '关闭',
              })
                  .then(() => {
                    // on confirm
                    this.$router.replace({
                      path: '/changePhone',
                      name: 'ChangePhone',
                    })
                  })
                  .catch(() => {
                    // on cancel

                  });
            } else {
              this.$dialog.toast({
                mes: res.msg || '验证码发送失败，请重新发送',
                timeout: 1500
              })
            }
          }).catch(() => {
            this.$dialog.loading.close()
            this.phonecodeshow = true
            clearInterval(this.phonetimer)
            this.phonetimer = null
          })
        }
      }
    },

    /**
     * 表单验证
     */
    verify4phone() {
      if (this.loginType === 'acc') {
        if (this.phoneNumber === '') {
          this.$dialog.toast({
            mes: '请输入手机号码！',
            timeout: 1500
          })
          return false
        } else if (!phone(this.phoneNumber)) {
          this.$dialog.toast({
            mes: '请输入正确的11位手机号码！',
            timeout: 1500
          })
          return false
        }
      } else {
        if (this.form.phoneNumber === '') {
          this.$dialog.toast({
            mes: '请输入手机号码！',
            timeout: 1500
          })
          return false
        } else if (!phone(this.form.phoneNumber)) {
          this.$dialog.toast({
            mes: '请输入正确的11位手机号码！',
            timeout: 1500
          })
          return false
        }
      }
      if (this.loginType === 'acc') {
        if (this.password === '') {
          this.$dialog.toast({
            mes: '请输入密码！',
            timeout: 1500
          })
          return false
        }
      } else {
        if (this.form.smsCode === '') {
          this.$dialog.toast({
            mes: '请输入验证码！',
            timeout: 1500
          })
          return false
        }
      }
      return true
    },

    /**
     * web登录
     */
    login() {
      if (this.agree === false) {
        this.$dialog.toast({
          mes: '请同意并勾选《用户协议》和《隐私政策》',
          timeout: 1500
        })
        return
      }
      if (this.verify4phone()) {
        this.$openLoading()
        let data = ''
        if (this.loginType === 'code') {
          data = {
            phoneNumber: this.form.phoneNumber,
            smsCode: this.form.smsCode,
            reqTime: new Date().Format('yyyy-MM-dd hh:mm:ss'),
            type: 0
          }
        } else {
          data = {
            phoneNumber: this.phoneNumber,
            pwd: this.password,
            reqTime: new Date().Format('yyyy-MM-dd hh:mm:ss'),
            type: 1
          }
        }
        const signStr = JSON.stringify(data)// 仅处理
        data = {
          param: this.$getRsaCode(signStr)
        }
        this.$axios.post(url.unionList, data).then(res => {
          this.$closeLoading()
          if (res.code === '200') {
            if (res.data.length === 1) {
              if (res.data[0].status && res.data[0].status === 'TS') {
                Dialog.confirm({
                  title: '提示',
                  width: '260px',
                  messageAlign: 'left',
                  confirmButtonText: '进入工会',
                  confirmButtonColor: '#EB523C',
                  className: 'join-union-tip',
                  message: `您在多个工会有账号，您输入的密码与其他工会密码不一致，当前可访问<span style="color:#EB523C">${res.data[0].enterpriseName}</span>`,
                  allowHtml: true
                }).then(() => {
                  location.href = res.data[0].systemUrl1 + '&logoutRedirectUrl=' + location.href
                }).catch(() => {

                })
              } else {
                location.href = res.data[0].systemUrl1 + '&logoutRedirectUrl=' + location.href
              }
            } else if (res.data.length > 1) {
              this.$store.dispatch('setUnionList', res.data)
              this.$router.push(`/selectUnion`)
            } else {
              this.$dialog.toast({
                mes: '获取信息失败，请重试',
                timeout: 1500,
                icon: 'none'
              })
            }
          } else if (res.code === '8888' || res.code === 8888) {
            Dialog.confirm({
              title: '提示',
              message: res.msg,
              confirmButtonText: '更换手机号',
              cancelButtonText: '关闭',
            })
                .then(() => {
                  // on confirm
                  this.$router.replace({
                    path: '/changePhone',
                    name: 'ChangePhone',
                  })
                })
                .catch(() => {
                  // on cancel

                });
          } else {
            this.$dialog.toast({
              mes: `${res.msg}` || '登录失败',
              timeout: 1500,
              icon: 'none'
            })
          }
        }).catch((err) => {
          this.$closeLoading()
          this.$dialog.toast({
            mes: '登录失败',
            timeout: 1500,
            icon: 'none'
          })
        })
      }
    }
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  mounted() {
    const _this = this
    const ch = this.$refs.loginmain.clientHeight
    if (ch < 600) {
      this.auto = true
    } else {
      this.auto = false
    }
    if (_this.timer) {
      clearInterval(_this.timer)
      _this.timer = null
    }
    _this.timer = setInterval(() => {
      if (document.getElementById('phoneNumber')) {
        clearInterval(_this.timer)
        document.getElementById('phoneNumber').getElementsByTagName('input')[0].addEventListener('click', (e) => {
          this.show = false
          e.target.focus()
        })
        document.getElementById('code').getElementsByTagName('input')[0].addEventListener('click', (e) => {
          this.show = false
          e.target.focus()
        })
        document.getElementById('phoneNumber').getElementsByTagName('input')[0].addEventListener('blur', (e) => {
          this.show = true
        })
        document.getElementById('code').getElementsByTagName('input')[0].addEventListener('blur', (e) => {
          this.show = true
        })
      }
    }, 1000)
  }
}
</script>

<style type="text/scss" lang="scss">
.login-main {
  width: 100%;
  height: 100%;
  background: linear-gradient(0deg, #eff0f4 0%, #f2f3f6 100%);
  position: relative;
  overflow-x: hidden;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

  .main-close {
    height: $headerHeight;

    img {
      width: rem(32);
      height: rem(32);
      margin: rem(28) 0 rem(28) rem(30);
    }
  }

  .main-form {
    position: absolute;
    left: rem(40);
    top: rem(88 + 40);
    right: rem(40);
    background-color: #fff;
    border-radius: rem(20);
    padding-bottom: rem(90);

    .page-logo {
      display: block;
      margin: 0 auto;
      margin-top: rem(110);
      width: rem(534);
      height: rem(74);
    }

    .page-sub-logo {
      display: block;
      margin: 0 auto;
      margin-top: rem(60);
      width: rem(216);
      height: rem(42);
    }

    .form-inner {
      padding: 0 rem(35);

      .form {
        .identifying {
          width: rem(300);
          font-size: rem(28);
          @include font-color($mainColor);
        }

        .yd-cell-right {
          padding-right: 0;
          flex-shrink: 0;
        }

        .yd-cell-item:after {
          display: none;
        }

        margin-top: rem(70);

        .yd-cell {
          background-color: transparent;
        }

        .yd-cell-item {
          padding-left: 0;
          margin-bottom: rem(40);
          height: rem(88);
          background: #f8f8f8;
          border-radius: rem(44);
          padding: 0 rem(35);
          &.sms-code {
            margin-bottom: rem(30);
          }
        }

        .yd-cell-right {
          padding-right: 0;
          flex-shrink: 0;
        }

        .yd-cell-item:after {
          display: none;
        }

        .yd-cell:after {
          display: none;
        }

        .yd-input-password-open:after {
          color: #a6a6a6;
        }

        .yd-input-clear:after {
          font-size: rem(30);
          color: #ccc;
        }

        input {
          font-size: rem(32);
          font-family: PingFang SC;
          color: #333;
          border: none;
          font-weight: bold;
        }

        input::-webkit-input-placeholder {
          font-size: rem(30);
          font-family: PingFang SC;
          font-weight: 400;
          color: #a6a6a6;
        }

        .iosPwd {
          input[type='password'] {
            font-size: rem(32);

            &::placeholder {
              font-size: rem(30);
            }
          }
        }
      }

      .btns {
        text-align: center;

        .loginBtn {
          width: rem(610);
          height: rem(88);
          @include bg-color($mainColor);
          border-radius: rem(44);
          font-size: rem(32);
          font-family: PingFang SC;
          font-weight: 400;
          color: #ffffff;
          margin: 0 auto;
          margin-top: rem(30);
          &.disabled {
            background-color: #ccc;
            color: #f0f0f0
          }
        }

        .btns-item {
          display: flex;
          align-items: center;
          justify-content: space-between;

          &.botm {
            justify-content: flex-end;
          }

          .item-btn {
            display: inline-block;
            font-size: rem(26);
            font-family: PingFang SC;
            font-weight: 400;
            color: #333333;
            @include font-color($mainColor);
          }
        }
        .check-agreement {
          display: flex;
          align-items: center;
          margin-top: rem(20);
          font-size: rem(28);
          .van-checkbox {
            display: inline-block;
            margin-right: rem(10);
            .van-checkbox__icon--checked .van-icon {
              @include bg-color($mainColor) ;
              @include border-color(1px, solid,$mainColor);
            }
          }
          span{
            @include font-color($mainColor);
            text-decoration: underline;
          }
        }
      }
    }
  }

  .form-bottom {
    position: absolute;
    left: 0;
    right: 0;
    bottom: rem(20);

    &.auto {
      margin-top: rem(300);
      position: relative;
    }

    .form-register {
      width: rem(370);
      height: rem(88);
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fff;
      border-radius: rem(44);
      margin: 0 auto;
      margin-bottom: rem(50);

      .register-inner {
        text-align: center;
        font-size: rem(28);
        font-family: PingFang SC;

        span:nth-child(1) {
          color: #666666;
        }

        span:nth-child(2) {
          @include font-color($mainColor);
        }
      }
    }

    .form-footer {
      text-align: center;
      font-size: rem(20);
      font-family: PingFang SC;
      font-weight: 400;
      color: #999999;

      .footer-item {
        margin-bottom: rem(20);

        .item-label {
          margin-bottom: rem(5);
        }
      }
    }
  }
  .agreement-popup {
    width: 100%;
    height: 100%;
    .agreement-container {
      position: relative;
      width: 100%;
      height: 100%;
      display: flex;
      flex-direction: column;
      .iframe-container{
        flex: 1 1 auto;
        height: 100%;
        overflow: auto;
        -webkit-overflow-scrolling: touch;
        iframe {
          width: 100%;
          height: 100%;
        }
      }
      .agreement-btn {
        flex: 0 0 auto;
        width: rem(610);
        height: rem(88);
        @include bg-color($mainColor);
        border-radius: rem(44);
        font-size: rem(32);
        font-family: PingFang SC;
        font-weight: 400;
        color: #ffffff;
        margin: rem(10) auto;
      }
    }
  }
}

.join-union-tip {
  font-weight: bold;
  color: #333;

  .van-dialog__header {
    line-height: rem(100);
    padding-top: 0;
  }

  .van-dialog__message {
    color: #333;
    padding-left: rem(30);
    padding-right: rem(30);
    padding-top: 0;
  }
}
</style>
